<template>
  <div>
    <!-- 搜索栏 -->
    <div style="margin-bottom: 20px;">
      <el-input
        v-model="searchNickname"
        placeholder="搜索主播昵称或房间名称"
        style="width: 300px; margin-right: 10px;"
        clearable
        @keyup.enter.native="handleSearch"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch" />
      </el-input>
      <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      :header-cell-style="{ 'text-align': 'center' }"
      border
    >
      <el-table-column prop="id" label="ID" align="center" width="80" />
      <el-table-column label="主播头像" align="center" width="100">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.avatar"
            style="width: 50px; height: 50px; border-radius: 50%;"
            :src="scope.row.avatar"
            fit="cover"
          />
          <span v-else>无头像</span>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="房间名称" align="center" width="auto" />

      <el-table-column prop="nickname" label="主播昵称" align="center" width="100" />
      <el-table-column prop="room_id" label="房间ID" align="center" width="100" />
      <el-table-column prop="total_audience" label="总观众数" align="center" width="100" />
      <el-table-column label="粉丝占比" align="center" width="100">
        <template slot-scope="scope">
          {{ scope.row.fan_percentage }}%
        </template>
      </el-table-column>
      <el-table-column prop="highest_online" label="最高在线" align="center" width="100" />
      <el-table-column label="平均观看时长" align="center" width="120">
        <template slot-scope="scope">
          {{ formatWatchTime(scope.row.average_watch_time) }}
        </template>
      </el-table-column>
      <el-table-column prop="new_follow_count" label="新增关注" align="center" width="100" />
      <el-table-column prop="cheers_count" label="点赞数" align="center" width="100" />
      <el-table-column prop="comment_count" label="评论数" align="center" width="100" />
      <el-table-column label="礼物总额" align="center" width="120">
        <template slot-scope="scope">
          ¥{{ scope.row.gift_total }}
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" width="180">
        <template slot-scope="scope">
          {{ scope.row.created_at }}
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" width="180">
        <template slot-scope="scope">
          {{ scope.row.end_at }}
        </template>
      </el-table-column>
      <el-table-column label="直播时长" align="center" width="150">
        <template slot-scope="scope">
          {{ calculateLiveDuration(scope.row.created_at, scope.row.end_at) }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="tabListPage">
      <el-pagination
        :current-page="currentPage"
        :page-sizes="pageSizes"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { getLiveReportList } from '../../../libs/api'

export default {
  name: 'LiveDisData',
  data() {
    return {
      tableData: [],
      loading: false,
      searchNickname: '',
      currentPage: 1,
      pageSize: 20,
      totalCount: 0,
      pageSizes: [10, 20, 50, 100]
    }
  },
  created() {
    this.getReportList()
  },
  methods: {
    // 获取直播统计列表
    getReportList() {
      this.loading = true
      const params = {
        nickname: this.searchNickname || '',
        page: this.currentPage.toString(),
        size: this.pageSize.toString()
      }

      getLiveReportList(params)
        .then(res => {
          console.log('直播统计列表响应:', res)
          if (res && res.code === 1 && res.data) {
            this.tableData = res.data.data || []
            this.totalCount = res.data.total || 0
          } else {
            this.tableData = []
            this.totalCount = 0
            this.$message.warning(res.msg || '获取数据失败')
          }
        })
        .catch(err => {
          console.error('获取直播统计列表失败:', err)
          this.$message.error('获取直播统计列表失败')
          this.tableData = []
          this.totalCount = 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.getReportList()
    },
    // 重置
    handleReset() {
      this.searchNickname = ''
      this.currentPage = 1
      this.getReportList()
    },
    // 分页相关
    handleCurrentChange(val) {
      this.currentPage = val
      this.getReportList()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getReportList()
    },
    // 格式化观看时长（秒转分钟）
    formatWatchTime(seconds) {
      if (!seconds && seconds !== 0) return '-'
      const minutes = Math.floor(seconds / 60)
      const secs = seconds % 60
      if (minutes > 0) {
        return `${minutes}分${secs}秒`
      }
      return `${secs}秒`
    },
    // 计算直播时长
    calculateLiveDuration(startTime, endTime) {
      if (!startTime || !endTime) return '-'

      try {
        const start = new Date(startTime.replace(/-/g, '/'))
        const end = new Date(endTime.replace(/-/g, '/'))

        if (isNaN(start.getTime()) || isNaN(end.getTime())) {
          return '-'
        }

        const diff = Math.floor((end - start) / 1000) // 差值（秒）

        if (diff < 0) return '-'

        const hours = Math.floor(diff / 3600)
        const minutes = Math.floor((diff % 3600) / 60)
        const seconds = diff % 60

        if (hours > 0) {
          return `${hours}小时${minutes}分${seconds}秒`
        } else if (minutes > 0) {
          return `${minutes}分${seconds}秒`
        } else {
          return `${seconds}秒`
        }
      } catch (error) {
        console.error('计算直播时长失败:', error)
        return '-'
      }
    }
  }
}
</script>

<style scoped>
.tabListPage {
  margin-top: 30px;
  text-align: right;
}
</style>

